const express = require("express");
const https = require("https");
const fs = require("fs");
const options = {
  key: fs.readFileSync("./src/certificate/liqiantw.icu.key"),
  cert: fs.readFileSync("./src/certificate/liqiantw.icu_bundle.crt"),
};
const { expressToken } = require("./utils/index");
const app = express();
const port = 3000;

// require('./learn/read.js')
// require('./learn/path')
// require('./learn/clockProject/index')

// 解决跨域中间件
const cors = require("cors");
app.use(cors());

// 全局中间件
app.use((req, res, next) => {
  // 响应头加这个配置也可以解决跨域问题
  res.setHeader("Access-Control-Allow-Origin", "*");
  // 允许所有的HTTP请求方法
  res.setHeader("Access-Control-Allow-Methods", "*");
  next();
});

// 解析application/json格式数据的中间件
app.use(express.json());
// 解析application/x-www-form-urlencoded格式数据的内置中间件
app.use(express.urlencoded({ extended: false }));

// 解析token
expressToken(app);

// 注册路由模块,第1个参数为统一前缀，可以不要
// 成绩相关与头像昵称更换
const scoreRouter = require("./api/score");
app.use("/score", scoreRouter);
// 测试接口
const testRouter = require("./api/index")
app.use("/score", testRouter);
// 登录相关接口
const loginRouter = require("./api/login");
app.use("/server", loginRouter);
// 用户相关接口
const customerRouter = require("./api/customer");
app.use("/customer", customerRouter);

// 错误级别中间件
app.use((err, req, res, next) => {
  if (err.name === "UnauthorizedError") {
    return res.status(401).send({
      code: 401,
      message: "token无效",
    });
  }
  res.status(500).send(err.message);
});

// 托管静态资源
app.use(express.static("src/learn/clockProject/clock"));
// 如果希望在托管的静态资源访问路径之前， 挂载路径前缀
app.use("/static", express.static("src/learn/npm"));

https
  .createServer(options, app)
  .listen(port, () => console.log(`Example app listening on port ${port}!`));

// app.listen(port, () => console.log(`Example app listening on port ${port}!`))